<?php
namespace app\appclass\controller;
use app\AdminRest;

use app\ApiRest;
use app\appclass\model\CardList;
use app\appclass\model\CardLog;
use app\appclass\model\CardTime;
use app\appclass\model\CardUser;
use app\appclass\model\CardWater;
use app\appclass\model\ClassCard;
use app\appclass\model\ClassCate;
use app\appclass\model\ClassCoach;
use app\appclass\model\ClassDate;
use app\appclass\model\ClassLable;
use app\appclass\model\ClassList;
use app\appclass\model\ClassRecord;
use app\appclass\model\ClassRoom;
use app\appclass\model\Lable;
use app\appclass\model\StoreInfo;
use app\card\model\Company;
use app\card\model\UserPhone;
use app\shop\model\IndexUser;
use app\shop\model\IndexUserInfo;
use think\App;
use think\facade\Db;


class IndexStoreCard extends ApiRest
{

    protected $model;

    protected $record_model;

    protected $lable_model;

    protected $room_model;

    protected $date_model;

    protected $store_id;

    protected $class_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->class_model = new ClassList();

        $this->model       = new CardUser();

        $this->record_model= new ClassRecord();

        $this->card_model  = new CardList();

        $this->log_model   = new CardLog();

        $this->date_model  = new ClassDate();

        $this->store_id = $this->class_model->getStoreId($this->getUserId());

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-02 17:41
     * @功能说明:用户会员列表
     */
    public function cardUserList(){
        //初始化会员卡
        $this->model->initCard($this->_uniacid);

        $input = $this->_param;

        $dis[] = ['a.store_id','=',$this->store_id];

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_id','<>',0];
        //发卡时间
        if(!empty($input['create_start_time'])&&!empty($input['create_end_time'])){

            $create_start_time = $input['create_start_time'];

            $create_end_time   = $input['create_end_time'];

            $dis[] = ['a.create_time','between',"$create_start_time,$create_end_time"];

        }
        //有效期
        if(!empty($input['end_start_time'])&&!empty($input['end_end_time'])){

            $end_start_time = $input['end_start_time'];

            $end_end_time   = $input['end_end_time'];

            $dis[] = ['a.end_time','between',"$end_start_time,$end_end_time"];

        }
        //卡类型
        if(isset($input['card_type'])){

            $dis[] = ['a.card_type','=',$input['card_type']];

        }
        //体验卡/会员卡
        if(isset($input['effect'])){

            $dis[] = ['a.effect','=',$input['effect']];

        }
        //状态
        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];

        }else{

            $dis[] = ['a.status','>',-1];

        }

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['b.nickName','like','%'.$input['name'].'%'];

            $where[] = ['a.mobile','like','%'.$input['name'].'%'];
        }

        $data = $this->model->dataList($dis,10,$where);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 10:00
     * @功能说明:会员卡详情
     */
    public function cardUserInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        $user_model = new IndexUser();

       // $phone_model= new UserPhone();

        $data['nickName']  = $user_model->where(['id'=>$data['user_id']])->value('nickName');

        $data['avatarUrl'] = $user_model->where(['id'=>$data['user_id']])->value('avatarUrl');

        $data['gender']    = $user_model->where(['id'=>$data['user_id']])->value('gender');

      //  $data['mobile']    = $phone_model->where(['id'=>$data['user_id']])->value('phone');

        $data['end_time']     = date('Y-m-d H:i:s',$data['end_time']);

        $data['create_time']  = date('Y-m-d H:i:s',$data['create_time']);

        $data['open_time']    = date('Y-m-d H:i:s',$data['open_time']);

        $data['adviser_name'] = lbUserName($data['adviser']);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-20 10:14
     * @功能说明:会员卡预约记录
     */
    public function cardAppRecord(){

        $input = $this->_param;

        $dis = [

            'card_id' => $input['card_id']
        ];

        $record_model = new ClassRecord();

        $data = $record_model->dataList($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 14:18
     * @功能说明:停卡
     */
    public function stopCard(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        if($data['status']==4){

            $this->errorMsg('已停卡');
        }

        if($data['status']==5){

            $this->errorMsg('已退卡,无法停卡');

        }

        if($data['end_time']<time()){

            $this->errorMsg('卡已经过期');

        }

        $res = $this->model->controlCard($input['id'],4,$this->_uniacid,$this->getUserId());

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 14:18
     * @功能说明:退卡
     */
    public function returnCard(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        if($data['status']==5){

            $this->errorMsg('已经退卡');

        }

        $res = $this->model->controlCard($input['id'],5,$this->_uniacid,$this->getUserId(),1,$input['cancel_price'],$input['cancel_type']);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 15:02
     * @功能说明:删除卡
     */
    public function delCard(){

        $input = $this->_input;

        $res = $this->model->controlCard($input['id'],-1,$this->_uniacid,$this->getUserId());

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-09 11:44
     * @功能说明:开卡
     */
    public function openCard(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        if($data['status']!=4){

            $this->errorMsg('只有处于停卡状态的卡，才能开卡');

        }

        $log_model = new CardLog();
        //查询上一次停卡的信息
        $stop_info = $log_model->where(['card_user_id'=>$input['id'],'status'=>4])->order('create_time desc')->find();

        if(empty($stop_info)){

            $this->errorMsg('未找到上次停卡信息');

        }

        $stop_info = $stop_info->toArray();
        //过期时间
        $end_time = time()-$stop_info['create_time']+$data['end_time'];

        $status = 2;
        //判断状态
        if($data['open_time']>time()){

            $status = 1;
        }

        $update = [

            'end_time' => $end_time,

            'status'   => $status
        ];

        Db::startTrans();
        //修改会员卡信息
        $res = $this->model->dataUpdate($dis,$update);

        if($res==0){

            Db::rollback();

            $this->errorMsg('开卡失败');
        }
        //添加操作日志
        $res = $this->model->controlCard($input['id'],2,$this->_uniacid,$this->getUserId());

        if($res==0){

            Db::rollback();

            $this->errorMsg('开卡失败');
        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 17:50
     * @功能说明:会员卡列表
     */

    public function cardList(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['store_id','=',$this->store_id];

        if(!empty($input['title'])){

            $dis[] = ['title','like','%'.$input['title'].'%'];

        }
        //体验卡/会员卡
        if(isset($input['effect'])){

            $dis[] = ['effect','=',$input['effect']];

        }

        $data = $this->card_model->dataList($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-03 15:06
     * @功能说明:编辑会员卡
     */
    public function cardUserUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->model->dataInfo($dis);

        Db::startTrans();

        if(in_array($data['status'],[1,2,3])){

            $input['status'] = 2;

            if($input['open_time']>time()){

                $input['status'] = 1;
            }

//            if($input['end_time']<time()){
//
//                $input['status'] = 3;
//            }

            if($data['status']==1&&$input['status']==2){

                $res = $this->model->controlCard($input['id'],2,$this->_uniacid,$this->getUserId());

                if($res!=true){

                    Db::rollback();

                    $this->errorMsg('编辑失败3');
                }

            }

        }

        $res = $this->model->dataUpdate($dis,$input);
//        //添加流水记录
//        $water_model = new CardWater();
//
//        $res = $water_model->controlWater($data,$input['true_value'],$input['text'],$this->getUserId());
//
//        if($res==0){
//
//            Db::rollback();
//
//            $this->errorMsg('编辑失败2');
//        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-12 11:19
     * @功能说明:绑定会员
     */
    public function cardUserAdd(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        $res = $this->model->bindUser($input,$this->getUserId());

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-05-11 18:01
     * @功能说明:添加会员卡
     */

    public function cardAdd(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        $input['store_id']= $this->store_id;

        $res = $this->card_model->adminDataAdd($input);

        return $this->success($res);


    }



    /**
     * @author chenniang
     * @DataTime: 2021-05-11 18:18
     * @功能说明:会员卡详情
     */
    public function cardInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->card_model->dataInfo($dis);

        $card_time_model = new CardTime();

        $week['week'] = $card_time_model->where(['card_id'=>$data['id']])->group('week')->column('week');

        $week['time'] = $card_time_model->where(['card_id'=>$data['id']])->group('start_time')->select()->toArray();

        $week['week'] = !empty($week['week'])?array_values($week['week']):[];

        $data['card_time'] = $week;

        if(!empty($data['class_card'])){

            $class_model = new ClassList();

            foreach ($data ['class_card'] as &$v){

                $v['class_name'] = $class_model->where(['id'=>$v['class_id']])->value('title');

                $v['cate_id']    = $class_model->where(['id'=>$v['class_id']])->value('cate_id');

            }
        }

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-11 18:19
     * @功能说明:编辑会员卡
     */
    public function cardUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $input['uniacid'] = $this->_uniacid;

        $res = $this->card_model->adminDataUpdate($dis,$input);

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-05-13 16:38
     * @功能说明:修改会员卡状态
     */
    public function cardStatusUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $input['uniacid'] = $this->_uniacid;


        if(isset($input['status'])&&$input['status']==-1){

            $card_model = new CardUser();

            $where[] = ['card_id','=',$input['id']];

            $where[] = ['is_cancel','=',0];

            $where[] = ['end_time','>',time()];

            $find  = $card_model->dataInfo($where);

            if(!empty($find)){

                $this->errorMsg('该卡正在被使用');
            }

        }
        $res = $this->card_model->dataUpdate($dis,$input);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-09 14:28
     * @功能说明:会员卡变更记录
     */
    public function cardLogList(){

        $input = $this->_param;

        $dis = [

            'card_user_id' => $input['card_id']
        ];

        $log_model = new CardLog();

        $data = $log_model->dataList($dis);

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-09 14:30
     * @功能说明:会员卡记录
     */
    public function waterList(){

        $input = $this->_param;

        $water_model = new CardWater();

        $dis = [

            'card_id' => $input['card_id']

        ];

        $data = $water_model->waterList($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-06-30 17:33
     * @功能说明:续卡
     */
    public function renewCard(){

        $input = $this->_input;

        $log_model = new CardLog();

        $water_model= new CardWater();

        $card_model = new CardList();

        $card = $this->model->dataInfo(['id'=>$input['id']]);

        $top_card = $card_model->dataInfo(['id'=>$card['card_id']]);

        if(empty($top_card)||$top_card['status']==-1){

            $this->errorMsg('该会员卡已被删除');
        }

        Db::startTrans();

        $insert = [

            'uniacid'      => $this->_uniacid,

            'card_user_id' => $input['id'],

            'controller'   => $this->getUserId(),

            'status'       => 7,

            'create_time'  => time(),

            'price'        => $input['price'],

            'value'        => !empty($input['value'])?$input['value']:0,

            'before_value' => $card['true_value'],

            'after_value'  => !empty($input['value'])?$input['value']+$card['true_value']:$card['true_value'],

            'before_end_time' => $card['end_time'],

            'after_end_time'  => $input['end_time'],

            'text'          => $input['text'],

        ];

        $res = $log_model->insert($insert);

        if($res==0){

            Db::rollback();

            $this->errorMsg('续开失败');

        }

        $update = [

            'pay_price' => round($card['pay_price']+$input['price'],2),

            'true_value'=> $insert['after_value'],

            'end_time'  => $insert['after_end_time']

        ];

        $res = $this->model->dataUpdate(['id'=>$input['id']],$update);

        if($res==0){

            Db::rollback();

            $this->errorMsg('续开失败');

        }
        //期限卡没有
        if($card['card_type']!=0){
            //变更余额明细
            $res = $water_model->renewCardWater($card,$input['value'],'',$this->getUserId());

            if($res==0){

                Db::rollback();

                $this->errorMsg('续开失败');

            }

        }

        Db::commit();

        return $this->success($res);

    }






}
